<template>
  <div class="category-management">
    <!-- 统计卡片 -->
    <lay-card>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.total }}</div>
            <div class="stats-label">总分类数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.show }}</div>
            <div class="stats-label">显示中</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.hide }}</div>
            <div class="stats-label">已隐藏</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.maxLevel }}</div>
            <div class="stats-label">最大层级</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 操作区域 -->
    <lay-card style="margin-top: 16px;">
      <div class="toolbar">
        <div class="toolbar-left">
          <lay-button type="primary" @click="handleAdd">
            <lay-icon type="layui-icon-add-1"></lay-icon>
            新增分类
          </lay-button>
          <lay-button 
            type="danger" 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <lay-icon type="layui-icon-delete"></lay-icon>
            批量删除
          </lay-button>
          <lay-button @click="handleRefresh">
            <lay-icon type="layui-icon-refresh"></lay-icon>
            刷新
          </lay-button>
        </div>
        <div class="toolbar-right">
          <lay-input 
            v-model="searchForm.keyword" 
            placeholder="搜索分类名称"
            style="width: 200px; margin-right: 10px;"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <lay-icon type="layui-icon-search" @click="handleSearch"></lay-icon>
            </template>
          </lay-input>
          <lay-select 
            v-model="searchForm.isShow" 
            placeholder="显示状态"
            style="width: 120px; margin-right: 10px;"
            @change="handleSearch"
          >
            <lay-select-option value="">全部</lay-select-option>
            <lay-select-option :value="1">显示</lay-select-option>
            <lay-select-option :value="0">隐藏</lay-select-option>
          </lay-select>
          <lay-select 
            v-model="searchForm.level" 
            placeholder="分类级别"
            style="width: 120px;"
            @change="handleSearch"
          >
            <lay-select-option value="">全部</lay-select-option>
            <lay-select-option :value="1">一级分类</lay-select-option>
            <lay-select-option :value="2">二级分类</lay-select-option>
            <lay-select-option :value="3">三级分类</lay-select-option>
          </lay-select>
        </div>
      </div>
    </lay-card>

    <!-- 分类表格 -->
    <lay-card style="margin-top: 15px;">
      <lay-table 
        :columns="columns" 
        :data-source="tableData"
        :loading="loading"
        v-model:selectedKeys="selectedRowKeys"
        :default-toolbar="true"
        :pagination="false"
      >
        <template #level="{ row }">
          <lay-tag :type="getLevelTagType(row.level)">
            {{ getLevelText(row.level) }}
          </lay-tag>
        </template>
        
        <template #image="{ row }">
          <div v-if="row.image" class="category-image">
            <img :src="row.image" :alt="row.name" />
          </div>
          <span v-else class="no-image">无图片</span>
        </template>
        
        <template #isShow="{ row }">
          <lay-switch 
            :model-value="row.isShow === 1"
            @change="(value) => handleStatusChange(row, value)"
          ></lay-switch>
        </template>
        
        <template #action="{ row }">
          <lay-button size="xs" @click="handleEdit(row)">编辑</lay-button>
          <lay-button size="xs" type="primary" @click="handleAddChild(row)">添加子分类</lay-button>
          <lay-button size="xs" type="danger" @click="handleDelete(row)">删除</lay-button>
        </template>
      </lay-table>
      
      <!-- 自定义分页组件 -->
      <Pagination
        :total="pagination.total"
        :page="pagination.current"
        :page-size="pagination.pageSize"
        :page-size-options="pagination.limits"
        @change="handlePaginationChange"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </lay-card>

    <!-- 分类弹窗 -->
    <CategoryDialog 
      v-model="dialogVisible"
      :mode="dialogMode"
      :category-data="currentCategory"
      :parent-options="parentOptions"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { layer } from '@layui/layui-vue'
import { CategoryApi, type Category, type CategoryStats } from '../../../api/module/category'
import CategoryDialog from './components/CategoryDialog.vue'
import Pagination from '@/components/Pagination.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref<Category[]>([])
const selectedRowKeys = ref<string[]>([])
const stats = ref<CategoryStats>({
  total: 0,
  show: 0,
  hide: 0,
  levelStats: []
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  isShow: '' as string | number,
  level: '' as string | number
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showLimit: true,
  limits: [10, 20, 50, 100]
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const currentCategory = ref<Category | undefined>()
const parentOptions = ref<Category[]>([])

// 计算属性
const maxLevel = computed(() => {
  if (stats.value.levelStats.length === 0) return 0
  return Math.max(...stats.value.levelStats.map(item => item.level))
})

// 表格列配置
const columns = [
  {
    title: '分类名称',
    key: 'name',
    width: '200px'
  },
  {
    title: '分类级别',
    key: 'level',
    customSlot: 'level',
    width: '100px'
  },
  {
    title: '分类图片',
    key: 'image',
    customSlot: 'image',
    width: '120px'
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: '80px'
  },
  {
    title: '显示状态',
    key: 'isShow',
    customSlot: 'isShow',
    width: '100px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: '160px'
  },
  {
    title: '操作',
    key: 'action',
    customSlot: 'action',
    width: '200px',
    fixed: 'right'
  }
]

// 方法
const loadCategoryList = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 只有当搜索条件不为空时才添加到参数中
    if (searchForm.keyword && searchForm.keyword.trim()) {
      params.keyword = searchForm.keyword.trim()
    }
    
    if (searchForm.isShow !== '' && searchForm.isShow !== null && searchForm.isShow !== undefined) {
      params.isShow = Number(searchForm.isShow)
    }
    
    if (searchForm.level !== '' && searchForm.level !== null && searchForm.level !== undefined) {
      params.level = Number(searchForm.level)
    }
    
    console.log('搜索参数:', params) // 调试日志
    
    const response = await CategoryApi.getCategoryList(params)
    tableData.value = response.data.list
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取分类列表失败:', error)
    layer.msg('获取分类列表失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await CategoryApi.getCategoryStats()
    stats.value = response.data
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

const loadParentOptions = async () => {
  try {
    const response = await CategoryApi.getCategoryTree(1)
    parentOptions.value = response.data
  } catch (error) {
    console.error('获取父分类选项失败:', error)
  }
}

const handleSearch = () => {
  console.log('搜索条件:', searchForm)
  pagination.current = 1 // 重置到第一页
  loadCategoryList()
}

const handleRefresh = () => {
  console.log('重置搜索条件')
  searchForm.keyword = ''
  searchForm.isShow = ''
  searchForm.level = ''
  pagination.current = 1 // 重置到第一页
  loadCategoryList()
  loadCategoryStats()
}

// 分页变化处理
const handlePaginationChange = (page: number, pageSize: number) => {
  console.log('分页变化:', page, pageSize)
  pagination.current = page
  pagination.pageSize = pageSize
  loadCategoryList()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  console.log('页码变化:', page)
  pagination.current = page
  loadCategoryList()
}

// 每页数量变化处理
const handlePageSizeChange = (pageSize: number) => {
  console.log('每页数量变化:', pageSize)
  pagination.pageSize = pageSize
  pagination.current = 1 // 重置到第一页
  loadCategoryList()
}

const handleAdd = () => {
  dialogMode.value = 'create'
  currentCategory.value = undefined
  dialogVisible.value = true
}

const handleEdit = (category: Category) => {
  dialogMode.value = 'edit'
  currentCategory.value = { ...category }
  dialogVisible.value = true
}

const handleAddChild = (category: Category) => {
  if (category.level >= 3) {
    layer.msg('分类层级不能超过3级', { icon: 2 })
    return
  }
  
  dialogMode.value = 'create'
  currentCategory.value = {
    name: '',
    parentId: category.id!,
    level: category.level + 1,
    sortOrder: 0,
    isShow: 1
  }
  dialogVisible.value = true
}

const handleDelete = (category: Category) => {
  layer.confirm(`确定要删除分类"${category.name}"吗？`, {
    icon: 3,
    title: '删除确认'
  }, async () => {
    try {
      await CategoryApi.deleteCategory(category.id!)
      layer.msg('删除成功', { icon: 1 })
      loadCategoryList()
      loadStats()
    } catch (error: any) {
      layer.msg(error.response?.data?.message || '删除失败', { icon: 2 })
    }
  })
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    layer.msg('请选择要删除的分类', { icon: 2 })
    return
  }
  
  layer.confirm(`确定要删除选中的${selectedRowKeys.value.length}个分类吗？`, {
    icon: 3,
    title: '批量删除确认'
  }, async () => {
    try {
      const ids = selectedRowKeys.value.map(key => Number(key))
      await CategoryApi.deleteCategories(ids)
      layer.msg('批量删除成功', { icon: 1 })
      selectedRowKeys.value = []
      loadCategoryList()
      loadStats()
    } catch (error: any) {
      layer.msg(error.response?.data?.message || '批量删除失败', { icon: 2 })
    }
  })
}

const handleStatusChange = async (category: Category, value: boolean) => {
  try {
    const isShow = value ? 1 : 0
    await CategoryApi.updateCategoryStatus(category.id!, isShow)
    category.isShow = isShow
    layer.msg('状态更新成功', { icon: 1 })
    loadStats()
  } catch (error: any) {
    layer.msg(error.response?.data?.message || '状态更新失败', { icon: 2 })
  }
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadCategoryList()
  loadStats()
  loadParentOptions()
}

const getLevelText = (level: number) => {
  const levelMap: Record<number, string> = {
    1: '一级分类',
    2: '二级分类',
    3: '三级分类'
  }
  return levelMap[level] || '未知'
}

const getLevelTagType = (level: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'normal',
    3: 'warm'
  }
  return typeMap[level] || 'primary'
}

// 生命周期
onMounted(() => {
  loadCategoryList()
  loadStats()
  loadParentOptions()
})
</script>

<style scoped>
.category-management {
  padding: 15px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.category-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
}

.category-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #999;
  font-size: 12px;
}
</style>